package com.mou.aiagent.controller;
import com.mou.aiagent.agent.model.MouManus;
import com.mou.aiagent.app.LoveApp;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;

@RestController
@RequestMapping("/ai")
@Slf4j
public class AiController {
    @Resource
    private LoveApp loveApp;
    @Resource
    private MouManus mouManus;
    @Resource
    private ToolCallback[] toolCallbacks;
    @Resource
    private ChatModel dashboardChatModel;

    /**
     * 同步AI 恋爱大师会话
     * @param message
     * @param chatId
     * @return
     */
    @GetMapping ("/love_app/chat/sync")// 设置请求方法为GET
    public String doChatWithLoveAppSync( String message ,String chatId) {
       log.info("message:{},chatId:{}",message,chatId);
        return loveApp.doChat(message,chatId);
    }

    /**
     * 流式AI 恋爱大师会话
     * @param message
     * @param chatId
     * @return
     */
    @GetMapping(value = "/love_app/chat/sse",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> doChatWithLoveAppSSE(String message, String chatId) {
        return loveApp.doChatByStream(message, chatId);
    }
    @GetMapping("/love_app/chat/sse_emitter")
    public SseEmitter doChatWithLoveAppSseEmitter(String message, String chatId) {
        // 创建一个SseEmitter对象
        SseEmitter emitter = new SseEmitter(180000L); // 设置超时时间为3分钟
        // 在这里处理业务逻辑，并将结果通过SseEmitter发送给客户端
        loveApp.doChatByStream(message, chatId).subscribe(chunk -> {
            try {
                emitter.send(chunk);
            }catch (IOException e){
                emitter.completeWithError(e);
            }
        },emitter::completeWithError, emitter::complete);
        return emitter;
    }

    /**
     * 流式AI超级智能体 恋爱大师会话
     * @param message
     * @return
     */
    @GetMapping("/manus/chat")
    public SseEmitter doChatWithManus(String message) {
        MouManus manus = new MouManus(toolCallbacks, dashboardChatModel);
        return manus.runStream(message);
    }
}
